package org.wanho.servlet;

import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.wanho.util.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Author：汤小洋
 * Date：2023-04-25 15:14
 * Description：<描述>
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            List<FileItem> items = upload.parseRequest(req);
            for(FileItem item : items){
                // 判断是普通文本还是文件
                if (item.isFormField()){ // 普通文本
                    System.out.println("参数名："+item.getFieldName());
                    System.out.println("参数值："+item.getString());
                }else{ // 文件
                    System.out.println("文件名：" +item.getName());
                    System.out.println("文件大小：" + item.getSize());
                    System.out.println("文件类型：" +item.getContentType());
                    System.out.println("文件内容：" + item.getInputStream());


                    resp.setContentType("application/json;charset=utf8");
                    PrintWriter out = resp.getWriter();
                    out.print(JSON.toJSONString(ResponseResult.success()));
                    out.close();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
